package org.dromara.nursing.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.nursing.domain.bo.ContractManageBo;
import org.dromara.nursing.domain.vo.ContractManageVo;
import org.dromara.nursing.domain.ContractManage;
import org.dromara.nursing.mapper.ContractManageMapper;
import org.dromara.nursing.service.IContractManageService;
import org.dromara.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.stp.StpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 合同Service业务层处理
 *
 * @author Xue
 * @date 2025-04-25
 */
@RequiredArgsConstructor
@Service
public class ContractManageServiceImpl implements IContractManageService {

    private static final Logger log = LoggerFactory.getLogger(ContractManageServiceImpl.class);
    private final ContractManageMapper baseMapper;
    private static final String FAMILY_ROLE_KEY = "family_user";
    private static final String ADMIN_ROLE_KEY = "admin";
    private static final String SUPER_ADMIN_ROLE_KEY = "superadmin";

    /**
     * 查询合同
     *
     * @param contractId 主键
     * @return 合同
     */
    @Override
    public ContractManageVo queryById(Long contractId){
        ContractManageVo contract = baseMapper.selectVoById(contractId);
        
        // 检查是否为家属角色并验证权限
        if (contract != null && StpUtil.hasRole(FAMILY_ROLE_KEY)) {
            Long userId = LoginHelper.getUserId();
            if (userId != null && !isContractBelongsToUser(contractId, userId)) {
                log.warn("用户 {} 尝试访问非关联老人合同 {}", userId, contractId);
                return null; // 家属无权查看非关联老人的合同
            }
        }
        
        return contract;
    }

    /**
     * 分页查询合同列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 合同分页列表
     */
    @Override
    public TableDataInfo<ContractManageVo> queryPageList(ContractManageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ContractManage> lqw = buildQueryWrapper(bo);
        Page<ContractManageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的合同列表
     *
     * @param bo 查询条件
     * @return 合同列表
     */
    @Override
    public List<ContractManageVo> queryList(ContractManageBo bo) {
        LambdaQueryWrapper<ContractManage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ContractManage> buildQueryWrapper(ContractManageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ContractManage> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ContractManage::getContractId);
        lqw.like(StringUtils.isNotBlank(bo.getElderName()), ContractManage::getElderName, bo.getElderName());
        lqw.eq(StringUtils.isNotBlank(bo.getIdCard()), ContractManage::getIdCard, bo.getIdCard());
        lqw.like(StringUtils.isNotBlank(bo.getContactName()), ContractManage::getContactName, bo.getContactName());
        
        // 如果是家属角色，只能查看自己关联的老人合同
        if (StpUtil.hasRole(FAMILY_ROLE_KEY)) {
            Long userId = LoginHelper.getUserId();
            if (userId != null) {
                log.info("家属用户 {} 正在查询关联老人合同", userId);
                lqw.eq(ContractManage::getContactUserId, userId); // 假设合同表中有contactUserId字段关联用户
            }
        }
        
        return lqw;
    }

    /**
     * 检查合同是否属于当前用户(家属)
     *
     * @param contractId 合同ID
     * @param userId 用户ID
     * @return 是否属于
     */
    private boolean isContractBelongsToUser(Long contractId, Long userId) {
        LambdaQueryWrapper<ContractManage> lqw = Wrappers.lambdaQuery();
        lqw.eq(ContractManage::getContractId, contractId);
        lqw.eq(ContractManage::getContactUserId, userId);
        return baseMapper.selectCount(lqw) > 0;
    }

    /**
     * 新增合同
     *
     * @param bo 合同
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ContractManageBo bo) {
        ContractManage add = MapstructUtils.convert(bo, ContractManage.class);
        validEntityBeforeSave(add);
        
        // 如果是家属角色，设置当前用户为联系人用户ID
        if (StpUtil.hasRole(FAMILY_ROLE_KEY)) {
            Long userId = LoginHelper.getUserId();
            if (userId != null) {
                add.setContactUserId(userId);
            }
        }
        
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setContractId(add.getContractId());
        }
        return flag;
    }

    /**
     * 修改合同
     *
     * @param bo 合同
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ContractManageBo bo) {
        // 检查家属角色权限
        if (StpUtil.hasRole(FAMILY_ROLE_KEY)) {
            Long userId = LoginHelper.getUserId();
            Long contractId = bo.getContractId();
            
            if (userId != null && contractId != null && !isContractBelongsToUser(contractId, userId)) {
                log.warn("用户 {} 尝试修改非关联老人合同 {}", userId, contractId);
                return false; // 家属无权修改非关联老人的合同
            }
        }
        
        ContractManage update = MapstructUtils.convert(bo, ContractManage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ContractManage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除合同信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        // 如果是家属角色，检查是否有权限删除
        if (StpUtil.hasRole(FAMILY_ROLE_KEY)) {
            Long userId = LoginHelper.getUserId();
            if (userId != null) {
                for (Long id : ids) {
                    if (!isContractBelongsToUser(id, userId)) {
                        log.warn("用户 {} 尝试删除非关联老人合同 {}", userId, id);
                        return false; // 家属无权删除非关联老人的合同
                    }
                }
            }
        }
        
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
